class Item < ActiveRecord::Base
	
    has_one :item_statistic
    has_one :recommend_item
    belongs_to :user
    belongs_to :taobaoke_item, :class_name => "TaobaokeItem"

    named_scope :valid_items, :conditions => ["status >= 0"]
    named_scope :top_item, lambda{|cid,iid| {:select => 'items.id, items.title, items.cat1_id, items.price', :conditions => ["items.cat1_id = ? and items.id <> ?", cid, iid], :limit => 10, :joins => "left join taobaoke_items on taobaoke_items.id = items.taobaoke_item_id", :order => "taobaoke_items.commission_volume desc"}}
    
    named_scope :search, lambda {|con|
      condition=[]
      unless con[:cid].nil?
      condition << "cat1_id=?"
      condition << con[:cid]
      end
      unless con[:nick].nil?
      condition << 'nick=?'
      condition << con[:nick]
      end
      
      reg=''
      if !con[:prop].nil?&&con[:prop].length>0
        reg = "%#{con[:prop].join('%')}%"
        condition[0] += " and props like ?"
        condition<< reg
      end
      {:conditions=>condition,:order=>'rand()',:select=>'pic_url,location,title,id,cat1_id,price'}
    }
    
    named_scope :keyword, lambda {|k,c,option|
      param = []
      sql=[]
      if !k.nil? && k.length>0
        ks = k.split("_")
        if ks.length>1
          sql << 'title like ? or title like ?'
          param << "%#{ks[0]}%#{ks[1]}%"
          param << "%#{ks[1]}%#{ks[0]}%"
        else
          sql << 'title like ?'
          param << "%#{k}%"
        end
      end
      if !c.nil? && c.length>0
        sql << "(cat1_id in (?)) "
        param << c.split("\/").join(",")
      end
      
      unless option.nil?
        if !option[:price_from].nil? && /^[1-9]\d*$/ =~ option[:price_from]
          sql << " price >= ?"
          param << option[:price_from]
        end
        if !option[:price_to].nil? && /^[1-9]\d*$/ =~ option[:price_to]
          sql << " price<= ? "
          param << option[:price_to]
        end
      end
      {:conditions=>[sql.join(' and ')]+param,:order=>'delist_time desc,sort_order',:select=>'pic_url,location,title,id,cat1_id,price'}
    }
    
    named_scope :recommend_item, lambda{|type, flag, limit|
     {:order=>'position asc',:conditions=>['recommend_type =? and r.flag = ?',type, flag],:select=>'i.title,i.price,i.click_url,i.pic_url,i.id,i.cat1_id',:joins=>'i join recommend_items r on r.related_id=i.id',:limit=>limit}
    }
    named_scope :top_commission_volume, lambda{|col| {:select => 'items.id, items.title, items.cat1_id, items.pic_url, items.price', :joins => "left join taobaoke_items on items.taobaoke_item_id = taobaoke_items.id", :order => "taobaoke_items.commission_volume desc", :limit => col}}
    named_scope :top_item_by_created_at, lambda{|col| {:select => 'items.id, items.title, items.cat1_id, items.pic_url, items.price', :limit => col, :order => 'created_at desc'}}
    
		def reverse_property_values
			property_values = {}
			properies = []
			properies = self.props.split(";") unless self.props.blank?
			conditions = ''
			properies.each_with_index do |prop, i|
				pps = prop.split(":")
				cid = get_cat_id
				conditions += "(cid = #{cid} and pid = #{pps[0]} and vid = #{pps[1]}) "
				conditions += " or " unless i == properies.length - 1
			end
			PropertyValue.find(:all, :select => 'id, property_name, name', :conditions => conditions, :order => 'sort_order asc')
		end
		
		def get_cat_id
    	self.cat1_id.nil? ? (self.cat2_id.nil? ? self.cat3_id : self.cat2_id) : self.cat1_id
  	end
  	
  	#浏览过此用户的还浏览过，暂随机取数据
  	def rand_item
  		Item.find(:all, :select => 'items.id, items.title, items.cat1_id, items.pic_url, items.price', :conditions => ["items.cat1_id = ? and items.id <> ?", self.cat1_id, self.id], :limit => 4, :order => 'rand()')
  	end

    #admin sql待优化#
    def self.admin_search(params, current_page, page_num)
			sort = params[:sort]
			if sort == 'by_created_at_desc' then order = "items.created_at desc"
			elsif sort == 'by_created_at_asc' then order = "items.created_at asc"
			elsif sort == 'by_price_asc' then order = "items.price asc"
			elsif sort == 'by_price_desc' then order = "items.price desc"			
			elsif sort == 'by_commission_desc' then order = "taobaoke_items.commission desc"
			elsif sort == 'by_commission_asc' then order = "taobaoke_items.commission asc"
			elsif sort == 'by_commission_rate_desc' then order = "taobaoke_items.commission_rate desc"
			elsif sort == 'by_commission_rate_asc' then order = "taobaoke_items.commission_rate asc"
			elsif sort == 'by_commission_num_desc' then order = "taobaoke_items.commission_num desc"
			elsif sort == 'by_commission_num_asc' then order = "taobaoke_items.commission_num asc"
			elsif sort == 'by_commission_volume_desc' then order = "taobaoke_items.commission_volume desc"
			elsif sort == 'by_commission_volume_asc' then order = "taobaoke_items.commission_volume asc"
			else order == "items.sort_order asc, items.id asc"
			end

			conditions = " items.status >= 0"
			conditions += " and items.cat1_id = #{params[:cat1_id]}" unless params[:cat1_id].blank?
			conditions += " and items.cat2_id = #{params[:cat2_id]}" unless params[:cat2_id].blank?
			conditions += " and items.cat3_id = #{params[:cat3_id]}" unless params[:cat3_id].blank?
			conditions += " and items.title like '%#{params[:item_title]}%'" unless params[:item_title].blank?
			
			Item.paginate(:all, :page => current_page, :per_page => page_num, :conditions => conditions, :order => order, :joins => 'left join item_statistics on items.id = item_statistics.item_id left join taobaoke_items on taobaoke_items.id = items.taobaoke_item_id', :include => [:item_statistic, :taobaoke_item])
		end
end  
